import React from 'react';
import ApplyStep from '@/components/ApplyStep';
import PageHeaderWrapper from '@/components/PageHeaderWrapper';
import { withRoutePage } from '@/utils/enhanceUtils';
import { connect } from 'umi';
import { withRouter } from 'umi';
import { countryDict } from '@/models/mineList';
import { readStatusMap, useSetReadStatus } from '@/hooks/useSetReadStatus';

import Forms from './Forms';
import { useData, useDynamicTitle } from './utils';

/**
 * @param location
 * @param portal 是否是企业管理
 * @param user 登录用户信息
 * @returns {*}
 */
const ApplyLeave = ({ location, user, dispatch }) => {
    const findCompany = curCompanyId => {
        if (!curCompanyId) return '';
        return countryDict.find(country => country.id === curCompanyId);
    };
    const {
        query: { processInstanceId, processTemplateId, leaveOfficeId, otherPost, type }
    } = location;
    useDynamicTitle(otherPost, dispatch, location);
    const { currentUser } = user;
    const getFetchParam = () => {
        if (leaveOfficeId) {
            return {
                processInstanceId,
                leaveOfficeId
            };
        }
        return {
            processTemplateId
        };
    };

    const { loading, detail } = useData(type === 'company', ...getFetchParam());
    const {
        processTaskInstances,
        processTaskTemplates,
        currentProcessTaskInstance,
        currentEmployeeProcessTaskTemplateId
    } = detail;
    const { relatedBusinessObject = {}, taskPath = '', assigneeEmployeeIds = '' } = currentProcessTaskInstance;
    const { lastConfirmDate = '', currentProcessTasDesc = '' } = relatedBusinessObject;
    // 是否是当前操作节点的操作人
    const isCurrentEditor = leaveOfficeId ? assigneeEmployeeIds.split(',').includes(`${currentUser.id}`) : true;
    let isEdit = !leaveOfficeId || assigneeEmployeeIds.split(',').includes(`${currentUser.id}`);
    // 查看者处于第几步骤
    let current;

    useSetReadStatus({ id: processInstanceId, type: readStatusMap.LEAVE });

    if (type === 'company') {
        isEdit = false;
        current = taskPath.length <= 3 ? 0 : taskPath.length / 3 - 2;
    } else if (leaveOfficeId) {
        if (isCurrentEditor) {
            current = taskPath.length / 3 - 1;
        } else {
            // eslint-disable-next-line max-len
            const findIndex = processTaskTemplates.findIndex(
                item => item.taskTemplateId === currentEmployeeProcessTaskTemplateId
            );

            if (findIndex !== -1) {
                current = findIndex;
            }
        }
    } else {
        current = 0;
    }
    // 流程到了第几步骤
    const applyCurrent = leaveOfficeId ? taskPath.length / 3 - 1 : 0;
    if (detail.processState === 'success') {
        isEdit = false;
        current = processTaskTemplates.length - 1;
    }

    const getStatus = (taskTemplateId, index) => {
        if (detail.processState === 'success') return 'finish';
        if (!leaveOfficeId) {
            if (index === 0) {
                return 'process';
            }
            return 'wait';
        }

        if (applyCurrent === index) return 'process';
        if (index < applyCurrent) return 'finish';
        const find = processTaskInstances.find(item => item.taskTemplateId === taskTemplateId);

        if (find && find.assigneeAction === 'backwardToPreviousTask') {
            return 'error';
        }
        return 'wait';
    };

    console.info('current:', current, ',isEdit:', isEdit);
    const country = findCompany(leaveOfficeId ? relatedBusinessObject.companyId : currentUser.companyId);

    return (
        <PageHeaderWrapper type="success">
            <ApplyStep
                title={
                    !otherPost &&
                    `离职申请-${country ? country.name : ''}-${
                        leaveOfficeId ? relatedBusinessObject.employeeName || '' : currentUser.employeeName
                    }`
                }
                loading={loading}
                processTaskTemplates={processTaskTemplates}
                processTaskInstances={processTaskInstances}
                currentProcessTaskInstance={currentProcessTaskInstance}
                lastConfirmDate={lastConfirmDate}
                status={currentProcessTasDesc}
                getStatus={getStatus}
                isSuccess={detail.processState === 'success'}
                currentUser={currentUser}
            >
                <Forms
                    current={current}
                    isEdit={isEdit}
                    detail={detail}
                    query={location.query}
                    currentUser={currentUser}
                />
            </ApplyStep>
        </PageHeaderWrapper>
    );
};
export default withRoutePage(connect(({ user }) => ({ user }))(withRouter(ApplyLeave)));
